<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use App\Jobs\ApplicationLog as ApplicationLogJob;

class ApplicationLog
{
    public function __construct()
    {

    }

    /**
     * @param Request $request
     * @param Closure $next
     * @param null $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $array = [
            'params'    => $request->all(),
            'header'    => $request->header(),
            'method'    => $request->method(),
            'url'       => $request->url(),
            'ip'        => $request->ip(),
            'port'      => $request->getPort()
        ];

        Log::info('Uri:' . $request->path(), $array);

        $time = time();
        $array = array_merge(
            $array,
            [
                'fullUrl' => $request->fullUrl(),
                'user' => $request->user(),
                'timestamp' => $time,
                'date' => date('Y-m-d H:i:s', $time)
            ]
        );
        try {
            if (env('app_env') === 'prod') {
                Queue::push(new ApplicationLogJob($array),'',ApplicationLogJob::QUEUE_NAME);
            }
        } catch (\Throwable $e) {
            Log::error($e, $e->getTrace());
        }
        return $next($request);
    }

}
